//
//  invoiceList_ViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 27-05-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "invoiceList_iPad_ViewController.h"
#import "classInvoiceCell.h"
#import "CustomCell.h"
#import "dao.h"

@interface invoiceList_iPad_ViewController ()

@end

@implementation invoiceList_iPad_ViewController

@synthesize tableViewInvoice;
@synthesize dataArrayInvoice = _dataArrayInvoice;
@synthesize json;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArrayInvoice count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault
                                 reuseIdentifier:CellIdentifier];
    }
    
    classInvoiceCell *objCell = [_dataArrayInvoice objectAtIndex:indexPath.row];
    
    cell.lblInvoice.text = objCell.lblInvoice;
    cell.lblDate.text = objCell.lblDate;
    
    cell.lblTotalAmount.text = [NSString stringWithFormat:@"%@",  [self formatCurrencyValue:[ objCell.lblTotalAmount doubleValue]]  ]; //objCell.lblTotalAmount;
    cell.lblInvoiceState.text = objCell.lblInvoiceState;
    
    return cell;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    classInvoiceCell *objCell = [_dataArrayInvoice objectAtIndex:indexPath.row];
    
    NSLog(@"invoice=%@", objCell.lblInvoice);
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    [prefs setObject:objCell.lblInvoice forKey:@"strNroInvoiceSelected"]; //Identifica el Id de departamento si la búsqueda es por este concepto
    
}

- (NSString *)stringByRemovingControlCharacters: (NSString *)inputString
{
    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
    NSRange range = [inputString rangeOfCharacterFromSet:controlChars];
    if (range.location != NSNotFound) {
        NSMutableString *mutable = [NSMutableString stringWithString:inputString];
        while (range.location != NSNotFound) {
            [mutable deleteCharactersInRange:range];
            range = [mutable rangeOfCharacterFromSet:controlChars];
        }
        return mutable;
    }
    return inputString;
}

-(NSString*) formatCurrencyValue:(double)value
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [numberFormatter setCurrencySymbol:@"$"];
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber *c = [NSNumber numberWithFloat:value];
    return [numberFormatter stringFromNumber:c];
}

- (void) retrieveDataSearch{
    
    [_dataArrayInvoice removeAllObjects];
    _dataArrayInvoice = [[NSMutableArray alloc] init];
    
    //--------
    dao *objDAO = [[dao alloc] init];
    
    int intIdUsuario = 0;
    intIdUsuario = [objDAO obtainCurrentIdUser];
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonRegistraNotaVenta.aspx?strJsonBase=JsonListaNotasVentas&strIdUsuario=%i", intIdUsuario];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Load invoices perfecto!!!");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"idnv":"66", "desfpag":"CONTADO WEBPAY", "desen":"NO ENVIADO", "neto":"1068178", "iva":"202953", "total":"1271131", "fecha":"08/10/2014", "desest":"VIGENTE", "iddir":"36", "direc":"Centenario de San Miguel", "numdir":"935", "desepag":"NO PAGADADO", "desciu":"Santiago", "descom":"Tiltil" }]
             
             json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             for (int i = 0; i<json.count; i++)
             {
                 NSString *strInvoice = [[json objectAtIndex:i] objectForKey:@"idnv"];
                 NSString *strDate = [[json objectAtIndex:i] objectForKey:@"fecha"];
                 NSString *strTotalAmount = [[json objectAtIndex:i] objectForKey:@"total"]; //[NSString stringWithFormat:@"%@",  [self formatCurrencyValue:[[[json objectAtIndex:i] objectForKey:@"total"] doubleValue]]  ];
                 NSString *strInvoiceState = [[json objectAtIndex:i] objectForKey:@"desen"];
                 
                 classInvoiceCell *objCell = [[classInvoiceCell alloc] initClassCell:strInvoice andDate:strDate andTotalAmount:strTotalAmount andInvoiceState:strInvoiceState];
                 
                 NSLog(@"objCell.lblTotalAmount =%@", objCell.lblTotalAmount);
                 
                 [_dataArrayInvoice addObject:objCell];
             }
             
             [self.tableViewInvoice reloadData];
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }
     }];
    //--------
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"segueInvoiceState"])
    {
        NSLog(@"Segue !!!!!!!");
        
    }
}

- (void)viewWillAppear:(BOOL)animated {

    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"ipad_header_portrait.png"] forBarMetrics:UIBarMetricsDefault];
    
    [self retrieveDataSearch];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (IBAction)backToHomeArea:(id)sender {
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}

@end
